<template>
    <div class="Main">
        <div class="w1440">
            <div class="flex_fsw">
                <div class="MainLeft w72">
                    <div class="MainForm bgwhite">
                        <el-form ref="ruleFormRef" :model="formData" :rules="formRules" class="article-form">
                            <!-- 标题输入 -->
                            <div class="item mb40">
                                <div class="title">
                                    标题
                                </div>
                                <el-form-item prop="title">
                                    <el-input v-model="formData.title" placeholder="请输入文章标题（2~30个字）" maxlength="30"
                                        show-word-limit clearable />
                                </el-form-item>
                            </div>



                            <!-- 内容输入 -->
                            <div class="item mb40">
                                <div class="title">
                                    内容
                                </div>
                                <el-form-item prop="content">
                                    <div class="editor-box">
                                        <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode"
                                            style="border-bottom: 1px solid #ccc" />
                                        <Editor :defaultConfig="editorConfig" :mode="mode" v-model="formData.content"
                                            style="height: 400px; overflow-y: hidden" @onCreated="handleCreated"
                                            @onChange="handleChange" @onDestroyed="handleDestroyed"
                                            @onFocus="handleFocus" @onBlur="handleBlur" @customAlert="customAlert"
                                            @customPaste="customPaste" />
                                    </div>
                                </el-form-item>
                            </div>
                            <!-- 展示封面选择 -->
                            <div v-if="false" :class="['item mb40', { requred: uploadAttr.hasCover > 0 }]">
                                <el-form-item label="展示封面">
                                    <div class="cover-row d-flex">
                                        <!-- <el-radio-group style="margin-bottom: 0;" v-model="uploadAttr.hasCover"
                                            @change="handleCoverTypeChange">
                                            <el-radio :value="true">封面图</el-radio>
                                            <el-radio :value="false">无图</el-radio>
                                        </el-radio-group> -->
                                        <p class="cor999">（注：最多只能上传三张图片）</p>
                                    </div>


                                    <!-- 单图上传 -->
                                    <div v-show="uploadAttr.hasCover > 0" class="upload-area">
                                        <el-upload ref="uploadImage" accept="image/*"
                                            :action="uploadApiUrl + '/app/common/upload'" list-type="picture-card"
                                            v-model:file-list="uploadAttr.fileList" name="Image"
                                            :before-upload="beforeUpload" :on-success="handleSingleSuccess"
                                            :on-error="handleError" :on-remove="handleRemove"
                                            :on-preview="handlePictureCardPreview">
                                            <el-icon>
                                                <Plus />
                                            </el-icon>
                                        </el-upload>
                                        <div class="upload-tip">
                                            <div>图片大小<span class="corMain">不要超过2M</span> </div>
                                            <div>
                                                优质的封面有利于推荐，格式支持JPEG、JPG、PNG
                                            </div>
                                        </div>
                                    </div>
                                </el-form-item>
                                <!-- tip -->
                                <div v-show="uploadAttr.coverTip" class="tip-require corMain">请上传展示封面</div>
                            </div>


                            <!-- 是否发起投票 -->
                            <div class="item ">
                                <el-form-item label="是否发起投票">
                                    <el-radio-group v-model="formData.hasVote">
                                        <el-radio :value="false">否</el-radio>
                                        <el-radio :value="true">是</el-radio>
                                    </el-radio-group>
                                </el-form-item>

                                <div v-if="formData.hasVote" class="voteBox">
                                    <div class="item mb40">
                                        <el-form-item label="投票标题" :prop="formData.hasVote ? 'voteTitle' : ''">
                                            <el-input v-model="formData.voteTitle" placeholder="请输入投票标题（2~20个字）"
                                                maxlength="20" show-word-limit clearable />
                                        </el-form-item>
                                    </div>
                                    <el-form-item label="投票选项" :prop="formData.hasVote ? 'voteOptions' : ''">
                                        <div class="options-list">
                                            <div v-for="(option, index) in formData.voteOptions" :key="index"
                                                class="option-item">
                                                <el-input v-model="option.value"
                                                    :placeholder="'选项 ' + (index + 1)"></el-input>
                                                <el-button type="danger" @click="removeOption(index)"
                                                    v-if="formData.voteOptions.length > 2">
                                                    <img src="../assets/images/close.png" alt="">
                                                </el-button>
                                            </div>
                                        </div>
                                        <el-button type="primary" @click="addOption" class="addOptionBtn">
                                            + 添加选项
                                        </el-button>
                                    </el-form-item>
                                    <div class="item">
                                        <el-form-item label="投票类型">
                                            <el-radio-group v-model="formData.voteType">
                                                <el-radio :label="1">单选</el-radio>
                                                <el-radio :label="2">多选</el-radio>
                                            </el-radio-group>
                                        </el-form-item>
                                    </div>
                                    <div class="item">
                                        <el-form-item label="投票有效期">
                                            <el-radio-group v-model="formData.expireTime">
                                                <el-radio :label="1">1天</el-radio>
                                                <el-radio :label="2">7天</el-radio>
                                                <el-radio :label="3">30天</el-radio>
                                                <el-radio :label="4">90天</el-radio>
                                            </el-radio-group>
                                        </el-form-item>
                                    </div>
                                </div>
                            </div>

                            <!-- 选择分类 -->
                            <div class="FormHuati mb40" @click="showTopic">
                                <!-- <div class="FormHuatiTit">
                                    分类/版块
                                </div> -->
                                <div class="item">
                                    <el-form-item label="分类-版块" prop="plateId">
                                        <div class="category-path d-flex">
                                            <div class="c-item">
                                                <el-select v-model="formData.categoryId" placeholder="请选择分类"
                                                    @change="handleCategoryChange" class="w100">
                                                    <el-option v-for="item in categoryArr" :key="item.id"
                                                        :label="item.name" :value="item.id" />
                                                </el-select>
                                            </div>
                                            <div class="c-item">
                                                <el-select v-model="formData.plateId" placeholder="请选择版块" class="w100">
                                                    <el-option v-for="item in forumArr" :key="item.id"
                                                        :label="item.title" :value="item.id" />
                                                </el-select>
                                            </div>
                                        </div>
                                    </el-form-item>
                                </div>
                            </div>


                            <!-- <div class="FormLoacltion mb40">
                                <a href="javascript:void(0)">
                                    <div class="icon"><img src="../assets/images/add.png" alt=""></div>
                                    所在位置
                                </a>
                            </div> -->

                            <!-- 发布按钮 -->
                            <div class="publishBox">
                                <div class="d-flex a-center">
                                    <el-form-item>
                                        <el-checkbox @change="changeAutoSaveDraft" v-model="autoSaveDraft" name="type">
                                            草稿自动保存
                                        </el-checkbox>
                                    </el-form-item>
                                    <a class="pointer" @click="scrollToTop">回到顶部</a>
                                </div>
                                <el-form-item>
                                    <el-button type="primary" @click="submitForm" :loading="submitting"
                                        class="publishBtn">
                                        {{ submitting ? '发布中...' : hasDraft == 0 ? '发布' : '发布草稿' }}
                                    </el-button>
                                </el-form-item>
                            </div>
                        </el-form>
                    </div>
                </div>
                <div class="MainLeftRight w26">
                    <!-- 热门帖子 -->
                    <HotPost />
                </div>
            </div>
        </div>
    </div>

    <!-- 选择话题弹窗 s -->
    <el-dialog class="accusation-dialog" v-model="accusationVisible" style="width:600px">
        <div class="reporDialog">
            <h3 class="font24 t-center h3 cor000">添加话题</h3>
            <div class="search-user add-topic">
                <div class="d-flex a-center searchBox">
                    <el-input placeholder="搜索话题" class="font16" v-model="formTopicData.tName"
                        @keyup.enter="onSearchUser()">
                    </el-input>
                    <div class="buttons cor999 d-flex a-center">
                        <i class="icon-btn">
                            <img src="../assets/images/search.png" alt="">
                        </i> |
                        <i class="icon-btn">
                            <img src="../assets/images/jia.png" alt="">
                        </i>
                    </div>
                </div>
                <!-- 搜索话题 -->
                <div class="search-topic">
                    <div class="topic-list search-topic-list">
                        <div class="topic-tip cor999 font16">
                            至少添加一个话题
                        </div>
                        <ul>
                            <li class="flex-row-jcsb line-sm">
                                <h3 class="h3 font18 pointer">
                                    # 云南三一文化话题1
                                </h3>
                                <span class="aon font18">1 讨论</span>
                            </li>
                            <li class="flex-row-jcsb line-sm">
                                <h3 class="h3 font18 pointer">
                                    # 云南三一文化话题2
                                </h3>
                                <span class="aon font18">2 讨论</span>
                            </li>
                        </ul>
                    </div>
                    <div class="page flex-jcc">
                        <!-- <el-pagination background @size-change="handleSizeChangeTopic"
                            @current-change="handleCurrentChangeTopic" :current-page="currentPageTopic" :page-size="10"
                            :pager-count="5" layout="total, prev, pager, next" :total="totalTopic">
                        </el-pagination> -->
                    </div>
                </div>
                <!-- <div class="create-topic">
                    <div class="topic-list create-topic-list">
                        <ul>
                            <li class="flex-row-jcsb line-sm">
                                <h3 class="h3 font18 pointer">
                                    # 云南三一文化话题1
                                </h3>
                                <span class="aon font18">1 讨论</span>
                            </li>
                            <li class="flex-row-jcsb line-sm">
                                <h3 class="h3 font18 pointer">
                                    # 云南三一文化话题2
                                </h3>
                                <span class="aon font18">2 讨论</span>
                            </li>
                        </ul>
                    </div>
                </div> -->
            </div>
        </div>
    </el-dialog>
    <!-- 选择话题弹窗 e -->

    <!-- 查看大图 -->
    <div class="view-maxImage">
        <el-dialog v-model="dialogVisible" center>
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>

    <!-- 添加选项弹窗 -->
    <el-dialog title="添加选项" :append-to-body="true" :close-on-click-modal="false" v-model="addOptionDialogVisible" width="400px">
        <el-form :model="addOptionForm" :rules="addOptionRules" ref="addOptionFormRef" label-width="100px">
            <el-form-item label="选项名称" prop="name">
                <el-input v-model="addOptionForm.name" placeholder="请输入选项名称" />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer d-flex j-center">
            <el-button @click="addOptionDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddOption">确定</el-button>
        </div>
    </el-dialog>



</template>
<script setup name="PublishUpdates">
import { upload, postApi } from '@/api';
import { computed, ref, reactive, onBeforeMount, shallowRef, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useCommonStore } from '@/store/Common';
import { storeToRefs } from 'pinia';
import HotPost from '@/components/HotPost.vue'; // 热门帖子
// 富文本编辑器
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { DomEditor } from '@wangeditor/editor';

// 路由
const router = useRouter();

// 公共store
const commonStore = useCommonStore();
// 读取 store 中的内容
const { token } = storeToRefs(commonStore);

/**
 * @name 添加选项
 */
const addOptionDialogVisible = ref(false); // 添加选项弹窗
const addOptionFormRef = ref(null); // 添加选项表单
const addOptionForm = reactive({ // 添加选项表单
    name: '', // 选项名称
})
const addOptionRules = reactive({ // 添加选项表单验证规则
    name: [
        { required: true, message: '请输入选项名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ]
})
// 打开添加选项弹窗
const addOption = () => {
    nextTick(() => {
        if( addOptionFormRef.value) {
            addOptionFormRef.value.clearValidate(); // 清空验证
        }
    })
    if(formData.value.voteOptions.length >= 10){ // 选项数量大于等于10
        ElMessage.error('选项数量不能超过10个'); // 提示
        return; // 退出
    }
    addOptionDialogVisible.value = true; // 显示添加选项弹窗
}
// 移除选项
const removeOption = (index) => { // 移除选项
    formData.value.voteOptions.splice(index, 1); // 移除选项
}
// 处理添加选项
const handleAddOption = () => {
    addOptionFormRef.value.validate((valid) => { // 验证
        if (valid) { // 验证通过
            formData.value.voteOptions.push({ // 添加选项
                value: addOptionForm.name, // 选项名称
            })
            addOptionDialogVisible.value = false; // 隐藏添加选项弹窗
            addOptionForm.name = ''; // 清空选项名称
        }
    }) 
}

// 页面数据
const hasDraft = ref(0); // 是否存在草稿
const submitting = ref(false);
const accusationVisible = ref(false); // 添加投票
const autoSaveDraft = ref(false); // 自动保存
// 图片上传相关属性
const uploadAttr = reactive({
    hasCover: true, // true-有图，false-无图
    fileList: [], // 封面图数组
    coverTip: false, // 封面图提示
})
const formData = ref({
    topicId: 2,
    title: '',
    content: '',
    discussId: 0, // 话题id
    categoryId: '', // 分类id
    plateId: '', // 版块
    media: [], // 文件
    type: 3, // 类型 3文章，4投票，默认文章
    cut: 0, // 帖子性质，0 普通贴 1 付费贴 2 红包贴，  默认普通贴
    hasVote: false, // 是否有投票
    vote: { // 投票
        title: '', // 标题
        type: 1, // 1单选，2多选
        options: [], // 投票选项
        expireTime: 1, // 投票有效期
    },
    voteTitle: '', // 投票标题，用来验证
    voteOptions: [], // 投票选项，用来验证
    voteType: 1, // 投票类型，1单选，2多选
    expireTime: 1, // 投票有效期，1天，7天，30天，90天
})

// 表单验证规则
const validatContent = (rule, value, callback) => {
    if (value == '<p><br></p>') {
        callback(new Error('请输入内容'))
    } else {
        callback()
    }
}
const validatVoteOptions = (rule, value, callback) => {
    if(value.length < 2 || value.length > 10){
        callback(new Error('选项数量在2-10个之间'));
    }else{
        callback();
    }
}
const formRules = reactive({
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入内容', trigger: 'change' },
        { validator: validatContent, trigger: 'change' }
    ],
    plateId: [
        { required: true, message: '请选择分类-版块', trigger: 'change' }
    ],
    voteTitle: [
        { required: true, message: '请输入投票标题', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' } 
    ],
    voteOptions: [
        { validator: validatVoteOptions, trigger: 'change' }
    ]
})

/**
 * 点击图片查看大图
 */
const dialogVisible = ref(false); // 大图弹窗
const dialogImageUrl = ref(''); // 大图地址
function handlePictureCardPreview(image) {
    dialogImageUrl.value = image.url; // 存储图片地址
    dialogVisible.value = true; // 显示大图弹窗
}


// 计算属性
// 上传接口地址
const uploadApiUrl = computed(() => import.meta.env.VITE_BASE_API);

// 生命周期
onBeforeMount(() => {
    // 判断是否存在草稿
    let draftId = router.currentRoute.value.query.draftId;
    if (draftId && draftId != null) {
        hasDraft.value = draftId; // 存在草稿
        // 获取草稿
        postApi.getDraftDetail(draftId).then((res) => {
            // 遍历数据，将Null转为空防止接口报错
            for (const key in res.result.postForm) {
                if (res.result.postForm[key] === null) {
                    res.result.postForm[key] = '';
                }
            }
            res.result.postForm.voteTitle = res.result.postForm.vote.title; // 投票标题
            res.result.postForm.voteOptions = res.result.postForm.vote.options; // 投票选项
            res.result.postForm.voteType = res.result.postForm.vote.type; // 投票类型
            res.result.postForm.expireTime = res.result.postForm.vote.expireTime; // 投票有效期
            res.result.postForm.draftId = draftId; // 草稿id
            formData.value = res.result.postForm;
        }).catch((err) => { })
    }
    // 获取分类
    getCategoryList();
})
onMounted(() => {
    // 获取是否存在自动保存草稿
    if (localStorage.getItem('autoSaveDraft') == 'true') {
        autoSaveDraft.value = true;
    }
})
// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
    // 如果用户有自动保存草稿，在组件卸载前进行保存
    if (autoSaveDraft.value) {
        if (!formData.value.title) return; // 标题为空不保存
        formData.value.vote.title = formData.value.voteTitle; // 投票标题
        formData.value.vote.type = formData.value.voteType; // 投票类型
        formData.value.vote.options = formData.value.voteOptions; // 投票选项
        formData.value.vote.expireTime = formData.value.expireTime; // 投票有效期
        if (hasDraft.value != 0) {
            // 存在草稿，更新
            postApi.updateDraft(formData.value).then((res) => { }).catch((err) => { })
        } else {
            // 不存在草稿，保存
            postApi.saveDraft(formData.value).then((res) => { }).catch((err) => { })
        }
    }
    const editor = editorRef.value;
    if (editor == null) return;

    editor.destroy();
});
// 是否自动保存
const changeAutoSaveDraft =  () => {
    if (autoSaveDraft.value) {
        localStorage.setItem('autoSaveDraft', 'true');
    } else {
        localStorage.removeItem('autoSaveDraft');
    }
}

// 方法
function beforeUpload(file) {
    const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt5M = file.size / 1024 / 1024 < 2;
    if (!isJPGorPNG) {
        ElMessage.error('只能上传 JPEG/JPG/PNG 格式的图片!')
        return false
    }
    if (!isLt5M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    if (uploadAttr.fileList.length >= 1) {
        ElMessage.error('图片数量超过限制!')
        return false
    }
    return true
}

// 图片改变隐藏提示
function handleCoverTypeChange() {
    uploadAttr.coverTip = false;
}

// 图片上传失败
function handleError(err, file, fileList) {
    console.log(err);
    ElMessage.error('上传失败，请重试！');
}

// 图片移除
function handleRemove(file, fileList) {
    console.log('remove')
}

// 单图上传成功
function handleSingleSuccess(response, file, fileList) {
    if (response.code == 200 || response.code == 0) {
        uploadAttr.coverTip = false;
    } else {
        ElMessage.error(response.msg);
        // 上传失败处理逻辑
        const index = uploadAttr.fileList.findIndex(f => f.uid === file.uid);
        if (index !== -1) {
            uploadAttr.fileList.splice(index, 1);
        }
    }
}

// 提交表单
const ruleFormRef = ref(null)
const submitForm = function () {
    if (!ruleFormRef.value) return;
    // if(uploadAttr.hasCover) {
    //     if(uploadAttr.fileList.length == 0) {
    //         uploadAttr.coverTip = true;
    //     }
    // }
    ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
            submitting.value = true;
            if (uploadAttr.hasCover) {
                uploadAttr.fileList.forEach(item => {
                    formData.value.media.push(item.response.result);
                })
            } else {
                formData.value.media = [];
            }
            formData.value.vote.title = formData.value.voteTitle; // 投票标题
            formData.value.vote.type = formData.value.voteType; // 投票类型
            formData.value.vote.options = formData.value.voteOptions; // 投票选项
            formData.value.vote.expireTime = formData.value.expireTime; // 投票有效期
            if (hasDraft.value != 0) {
                // 存在草稿，发布
                // 2. 先更新草稿，再发布
                postApi.updateDraft(formData.value).then((res) => { 
                    postApi.publishDraft(formData.value.draftId).then((res) => {
                        ElMessage.success('发布成功，请耐心等待管理员审核');
                        // 将表单title字段设为空，防止组件销毁时触发更新草稿接口
                        formData.value.title = '';
                        // 返回我的草稿页
                        router.push('/drafts');
                    }).catch((err) => { }).finally(() => {
                        submitting.value = false;
                    });
                }).catch((err) => { })
                
            } else {
                // 发布帖子
                postApi.savePost(formData.value).then((res) => {
                    ElMessage.success('发布成功，请耐心等待管理员审核');
                    // 重置表单
                    ruleFormRef.value.resetFields()
                    uploadAttr.fileList = [];
                    formData.value = {
                        topicId: 2,
                        title: '',
                        content: '',
                        discussId: 0, // 话题id
                        categoryId: '', // 分类id
                        plateId: '', // 版块
                        media: [], // 文件
                        type: 3, // 类型 3文章，4投票，默认文章
                        cut: 0, // 帖子性质，0 普通贴 1 付费贴 2 红包贴，  默认普通贴
                        hasVote: false, // 是否有投票
                        vote: { // 投票
                            title: '', // 标题
                            type: 1, // 1单选，2多选
                            options: [], // 投票选项
                            expireTime: 1, // 投票有效期
                        },
                        voteTitle: '', // 投票标题，用来验证
                        voteOptions: [], // 投票选项，用来验证
                        voteType: 1, // 投票类型，1单选，2多选
                        expireTime: 1, // 投票有效期，1天，7天，30天，90天
                    }
                }).catch((err) => { })
                    .finally(() => {
                        submitting.value = false;
                    })
            }


        } else {
            ElMessage.warning('请完善信息后再提交');
            return false;
        }
    })
}

// 获取分类-版块
// const getForumList = function() {
//     postApi.getForumList().then((res) => {
//         forumArr.value = res.result;
//         console.log(res)
//     }).catch((err) => {})
// }
// 获取分类
const categoryArr = ref([]); // 分类
const forumArr = ref([]); // 版块
const getCategoryList = function () {
    postApi.getCategoryList().then((res) => {
        let cateIndex = 0; // 分类下标
        // 将id转为数字，防止选择后不显示对应label
        res.data.filter((item, index) => {
            item.id = Number(item.id);
            if (item.id == formData.value.categoryId) { // 如果分类id和表单分类id相同，记录下标
                cateIndex = index; // 记录下标
            }
            item.plateList.filter(sub => {
                sub.id = Number(sub.id);
            }) 
        })
        categoryArr.value = res.data;
        forumArr.value = res.data[cateIndex].plateList;
    }).catch((err) => { })
}
// 选择分类改变版块
const handleCategoryChange = function () {
    let currentList = categoryArr.value.find(item => item.id == formData.value.categoryId).plateList;
    if (currentList.length > 0) {
        forumArr.value = currentList;
    } else {
        forumArr.value = [];
        formData.value.plateId = '';
    }
}

/**
 * 以下为编辑器所用方法、属性
 */
// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();

// 菜单配置，必须用 ref，重要！
const toolbarConfig = {};
// 排除菜单组，写菜单组 key 的值即可
toolbarConfig.excludeKeys = [
    'fullScreen',
    'codeBlock'
];
const editorConfig = {
    placeholder: '说些什么吧...',
    autoFocus: false, // 禁用自动聚焦
    MENU_CONF: {
        // 上传图片配置
        uploadImage: {
            async customUpload(file, insertFn) {
                // file 即选中的文件
                // 自己实现上传，并得到图片 url alt href
                // 最后插入图片
                const formData = new FormData();
                formData.append('Image', file);
                const res = await upload.uploadImg(formData);
                // 插入图片
                insertFn(res.result, res.result, res.result);
            }
        },
        // 上传视频配置
        uploadVideo: {
            async customUpload(file, insertFn) {
                console.log('file', file)
                // file 即选中的文件
                // 自己实现上传，并得到视频 url alt href
                // 最后插入视频
                const formData = new FormData();
                formData.append('Image', file);
                const res = await upload.uploadImg(formData);
                // 插入视频
                // 自定义插入视频HTML
                const videoHtml = `<video controls src="${decodeURI(res.result)}" style="width:100%;height=400px;"></video>`
                insertFn(videoHtml);
            }
        }
    },
    // 设置默认文本颜色为黑色
    defaultStyle: {
        color: '#333333'
    }
};

// 编辑器回调函数
const handleCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
    // 当前菜单排序和分组
    // setTimeout(() => {
    //     const toolbar = DomEditor.getToolbar(editor)
    //     const curToolbarConfig = toolbar.getConfig()
    //     console.log(curToolbarConfig.toolbarKeys) 

    // }, 0);
};
const handleChange = (editor) => {

};
const handleDestroyed = (editor) => {
};
const handleFocus = (editor) => {
};
const handleBlur = (editor) => {
    ruleFormRef.value.validateField('content');
};
const customAlert = (info, type) => {
};
// 自定义粘贴事件
// 注意：callback 是必须的，必须调用，否则粘贴事件会失效。
const customPaste = (editor, event, callback) => {
    console.log('ClipboardEvent 粘贴事件对象', event);
    const clipboardData = event.clipboardData;
    const html = clipboardData.getData('text/html');
    const text = clipboardData.getData('text/plain');

    // 自定义插入内容
    editor.insertText(event);
    event.preventDefault(); // 阻止默认粘贴行为
    // 返回值（注意，vue 事件的返回值，不能用 return）
    callback(false); // 返回 false ，阻止默认粘贴行为
    // callback(true) // 返回 true ，继续默认的粘贴行为
    // 如果有HTML内容，进行处理
    if (html) {
        // 创建临时DOM元素
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = html;

        // 遍历所有元素，移除 style.color 属性
        const elements = tempDiv.querySelectorAll('*');
        elements.forEach(el => {
            //   const element = el;
            //   if (element.style.color) {
            //     element.style.removeProperty('color');
            //   }
            // 也可以考虑移除 background-color 如果需要
            // if (element.style.backgroundColor) {
            //   element.style.removeProperty('background-color');
            // }
        });

        // 获取清理后的 HTML 字符串
        const cleanHtml = tempDiv.innerHTML;

        // 将处理后的HTML插入编辑器
        editor.dangerouslyInsertHtml(cleanHtml);
    } else if (text) {
        // 处理纯文本内容
        // 插入纯文本，并可以设置默认样式
        editor.insertText(text);
    }
};
/**
 * 编辑器所用方法结束
 */

/**
 * @name 滚动到顶部
 */
const scrollToTop = function () {
    window.scrollTo({ top: 0, behavior: 'smooth' }); // 平滑滚动到顶部 
}


</script>

<style lang="less" scoped>
.MainForm {
    .item.requred {
        :deep(.el-form-item__label) {
            &:before {
                content: "*";
                color: red;
                display: block;
                margin-right: 5px;
            }
        }
    }

    .tip-require {
        padding-left: 110px;
        margin-top: 10px;
        color: var(--el-color-danger);
        font-size: 12px;
    }

    .category-path {
        .c-item {
            width: 160px;

            &:not(:last-child) {
                margin-right: 20px;
            }
        }
    }

    .editor-box {
        border: solid 1px #ccc;
        border-radius: 4px;
        overflow: hidden;
    }

    .upload-area {
        margin-top: 20px;
    }

    .cover-row p {
        font-size: 12px;
        margin-left: 10px;
    }
}

.MainForm :deep(.el-form-item__content) {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.MainForm .title {
    font-size: 24px;
    color: #000000;
    line-height: 1;
    margin-bottom: 20px;
}

.MainForm :deep(.el-input__wrapper) {
    padding: 25px 30px;
    font-size: 16px;
}

.MainForm :deep(.el-input__count) {
    font-size: 16px;
    color: #999;
}

.MainForm :deep(.el-textarea__inner) {
    padding: 30px;
    font-size: 16px;
    padding-right: 110px;
}

.MainForm :deep(.el-textarea .el-input__count) {
    bottom: auto;
    line-height: 1;
    position: absolute;
    right: 30px;
    top: 30px;
}

.el-radio-group {
    margin-bottom: 20px;
}

.upload-tip {
    margin-top: 10px;
}

.MainForm .FormLoacltion {
    padding-top: 0;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner),
:deep(.el-radio__input.is-checked .el-radio__inner) {
    background: #FF4000;
    border-color: #FF4000;
}

:deep(.el-checkbox__input.is-checked+.el-checkbox__label),
:deep(.el-radio__label) {
    color: #000 !important;
}

.publishBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.publishBox a {
    margin-left: 20px;
    color: #666;
}

.publishBox .el-form-item {
    margin-bottom: 0 !important;
}

:deep(.el-checkbox__label) {
    color: #666;
}

.publishBox a:hover {
    color: #00753e;
}

:deep(.el-radio__inner:hover) {
    border-color: #FF4000 !important;
}

:deep(.el-form-item__label) {
    color: #000;
}


.public-note-container .publice-note-content {
    width: 800px;
}

.public-note-container .choose-type {
    height: 95px;
}

.public-note-container .choose-type .type-item {
    margin-right: 55px;
}

.public-note-container .choose-type .type-item .type-item {
    margin-right: 0;
}

.public-note-container .choose-type .type-item figure {
    margin-bottom: 10px;
}

.public-note-container .edit-content {
    padding-bottom: 30px;
}

.public-note-container .other-form {
    padding-top: 30px;
    padding-bottom: 10px;
}

.public-note-container .other-form .custom-form-item .label {
    width: 110px;
    line-height: 40px;
}

.public-note-container .other-form .custom-form-item .input {
    width: 630px;
}

.public-note-container .other-form .custom-form-item .input .el-form-item__content {
    line-height: 40px;
}

.public-note-container .other-form .custom-form-item .input .el-input__inner {
    height: 40px;
    line-height: 40px;
    padding-right: 30px;
}

.public-note-container .other-form .custom-form-item .input .el-input__icon {
    width: 25px;
    line-height: 40px;
}

.public-note-container .other-form .custom-form-item:not(:last-child) {
    margin-bottom: 15px;
}

.public-note-container .other-form .custom-form-item .cover-txt figure {
    width: 220px;
    height: 165px;
    border: dashed 1px #ddd;
    border-radius: 5px;
}

.public-note-container .other-form .custom-form-item .cover-txt figcaption {
    margin-top: 10px;
}

.public-note-container .other-form .custom-form-item .cover-txt p {
    width: 380px;
    text-align: left;
}

.public-note-container .public-part {
    height: 80px;
}

.public-note-container .public-part .my-btn {
    min-width: 110px;
}

.manuscript-box {
    width: 380px;
    background: linear-gradient(to bottom, #f8fbfe, #fdf8f8);
}

.manuscript-box>h2 {
    height: 60px;
    padding-right: 30px;
}

.manuscript-box>h2 .left-title {
    padding-left: 30px;
}

.manuscript-box>h2 .left-title:after {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 3px;
    height: 100%;
    border-radius: 3px;
    background: rgb(209, 49, 56);
}

.manuscript-box .manuscript-list ul {
    border-top: solid 1px #eee;
}

.manuscript-box .manuscript-list ul li {
    padding: 15px 0;
    padding-right: 10px;
    border-bottom: solid 1px #eee;
}

.manuscript-box .manuscript-list ul li .handel-icons {
    position: absolute;
    right: 0;
    top: 10px;
    z-index: 3;
}

.manuscript-box .manuscript-list ul li p {
    margin-top: 10px;
}

.upload-video {
    max-width: 450px;
    margin: 0 auto;
}

.upload-video .el-upload,
.upload-video .el-upload-dragger {
    width: 100%;
}

.upload-video .el-upload-dragger {
    height: 260px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.upload-video .el-upload-dragger .el-icon-upload {
    margin: 0 0 25px 0;
    font-size: 60px;
}

.search-user .el-form .el-input__inner {
    border: 0;
    height: 50px;
    border-radius: 50px;
    padding: 0 90px 0 50px;
    background-color: #f8f8f8;
}

.search-user .el-form .el-input__suffix {
    width: 80px;
}

.search-user .el-form .el-input__suffix .el-input__icon {
    line-height: 50px;
    width: 100%;
}

.search-user .user-list ul li {
    padding: 10px 0;
    border-bottom: solid 1px #eee;
}

.search-user .user-list ul li figure img {
    width: 55px;
    height: 55px;
    border-radius: 50%;
    border: solid 1px #eee;
    object-fit: cover;
}

.search-user.add-topic .buttons {
    line-height: 40px;
}

.search-user.add-topic .buttons i {
    padding: 0 10px;
    line-height: 40px;
}

.search-user.add-topic .el-form .el-input__inner {
    padding-right: 120px;
}

.search-user.add-topic .el-form .el-input__suffix {
    width: 110px;
}

.search-user.add-topic .topic-tip {
    height: 40px;
    border-bottom: solid 1px #eee;
    line-height: 40px;
}

.search-user.add-topic .topic-list ul li {
    margin-top: 25px;
    padding: 0;
}

.search-user.add-topic .topic-list ul li h3 {
    width: 500px;
    cursor: pointer;
}

.search-user.add-topic .topic-list ul li h3:hover {
    text-decoration: underline;
}

.search-user.add-topic .search-topic-list h3 {
    color: #00753E;
}

.actions .my-btn {
    min-width: 110px;
}

.custom-dialog.w680 .el-dialog {
    width: 680px;
    min-width: 300px;
}

.fixed-time-form .el-input__inner {
    height: 45px;
    line-height: 45px;
    padding-right: 30px;
    background-color: #f8f8f8;
    border: 0;
    width: 120px;
}

.fixed-time-form .day .el-input__inner {
    width: 170px;
}

.fixed-time-form .el-input__icon {
    width: 25px;
    line-height: 45px;
}

.ql-toolbar.ql-snow {
    display: none;
}

.ql-container.ql-snow {
    border: none;
}

.el-select-dropdown__item {
    padding: 0;
}

.search-topic-list .active {
    background-color: #eaeaea;
}

.select-topic,
.select-user {
    color: rgb(var(--rgb-main-color));
}

.select-topic div,
.select-user div {
    display: inline-block;
}

.see-maxImage {
    text-align: center;
}

.see-maxImage .el-dialog {
    width: auto;
    max-width: 90%;
    display: inline-block;
}

.el-select-dropdown__item {
    padding: 0 10px;
}

.searchBox {
    border: 1px solid #eee;
    border-radius: 6px;
    margin-top: 20px;
}

.searchBox :deep(.el-input__wrapper) {
    border: none;
    box-shadow: none;
}

.accusation-dialog .reporDialog {
    padding-bottom: 30px !important;
}

:deep(.el-form-item__label) {
    width: 110px;
}

.options-list {
    width: 100%;
}

.options-list .option-item {
    position: relative;
    margin-bottom: 20px;
}

.options-list .option-item .el-button {
    position: absolute;
    right: 30px;
    top: 50%;
    transform: translate(0px, -50%);
    background: transparent;
    padding: 0;
    border: none;
}

.MainForm .voteBox :deep(.el-input__wrapper) {
    padding: 15px 30px;
}
</style>
